import axios from 'axios';
import { serialize } from '@/common/util'
import NProgress from 'nprogress' // progress bar
import errorCode from '@/const/errorCode'
import { Message } from 'element-ui'
import 'nprogress/nprogress.css'
import qs from 'qs'
import router from '@/router'
import store from "@/store"; // progress bar style
axios.defaults.timeout = 5000;
axios.defaults.baseURL = '/';//后台地址
//Vue.prototype.HOST = '/api'
//拦截器
// 跨域请求，允许保存cookie
axios.defaults.withCredentials = true
// NProgress Configuration
NProgress.configure({
  showSpinner: false
})
axios.interceptors.request.use(config => {
  console.log(store, "store")
  NProgress.start() // start progress bar
  const isToken = (config.headers || {}).isToken === false
  let token = store.getters.access_token
  if (token && !isToken) {
    config.headers['Authorization'] = 'Bearer ' + token// token
  }
  // headers中配置serialize为true开启序列化
  console.log(config, "config")
  if (config.methods === 'post' && config.headers.serialize) {
    config.data = serialize(config.data)
    delete config.data.serialize
  }

  // 处理get 请求的数组 springmvc 可以处理
  if (config.method === 'get') {
    config.paramsSerializer = function (params) {
      return qs.stringify(params, { arrayFormat: 'repeat' })
    }
  }

  return config
}, error => {
  return Promise.reject(error)
})

// HTTPresponse拦截
axios.interceptors.response.use(

  res => {
    NProgress.done()
    return res
  },
  error => {
    NProgress.done()
    const status = Number(error.status) || 200
    const message = error.msg || errorCode[status] || errorCode['default']
    if (error.response) {
     
      let errMsg = ''
      switch (error.response.status) {
        // case 401:
        //   console.error('token is out of time');
        //   errMsg = '登录信息获取失败'
        //   break;
        case 500:
          errMsg = '系统异常: errorCode = 500'
          break
        case 503:
          errMsg = '系统异常: 503,后台服务未启动'
          break
        case 426:
          errMsg = '用户名或密码错误'
          break
        case 428:
          errMsg = '验证码错误'
          break
        case 401:
          errMsg = '登录失效，将重新获取用户信息'
          // DingTalkApi.util.domainStorage.removeItem({ name: 'login' })
          router.push({ path: '/login' })
          break
      }
      if (error.response.status === 401) {
      //  errMsg = '登录信息获取失败'
        // window.location.reload()
 
      } else if (errMsg) {
            Message({
              message: errMsg,
              type: 'error'
            })
      }
    }
    return Promise.reject(error.response)
  }
)



/**
 * 封装get方法
 * @param url
 * @param data
 * @returns {Promise}
 */

export function fetch(url, params = {}) {
  return new Promise((resolve, reject) => {
    axios.get(url, {
      params: params
    })
      .then(response => {
        resolve(response.data);
      })
      .catch(err => {
        reject(err)
      })
  })
}


/**
 * 封装post请求
 * @param url
 * @param data
 * @returns {Promise}
 */
export function post(url, data = {}) {
  return new Promise((resolve, reject) => {
    axios.post(url, data)
      .then(response => {
        resolve(response.data);
      }, err => {
        reject(err)
      })
  })
}

/**
* 封装patch请求
* @param url
* @param data
* @returns {Promise}
*/

export function patch(url, data = {}) {
  return new Promise((resolve, reject) => {
    axios.patch(url, data)
      .then(response => {
        resolve(response.data);
      }, err => {
        reject(err)
      })
  })
}

/**
* 封装put请求
* @param url
* @param data
* @returns {Promise}
*/

export function put(url, data = {}) {
  return new Promise((resolve, reject) => {
    axios.put(url, data)
      .then(response => {
        resolve(response.data);
      }, err => {
        reject(err)
      })
  })
}


/**
 * 封装DELETE请求
 * @param url
 * @param data
 * @returns {Promise}
 */

// export function cut(url,data = {}){
//   return new Promise((resolve,reject) => {
//     axios.delete(url,data)
//          .then(response => {
//            resolve(response.data);
//          },err => {
//            reject(err)
//          })
//   })
// }


export function cut(url, config) {
  return new Promise((resolve, reject) => {
    axios.delete(url, config)
      .then(response => {
        resolve(response.data);
      }, err => {
        reject(err)
      })
  })
}

export default axios